package com.mojo.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.List;
import java.util.Map;

/**
 * 事务实现-编程式事务(PlatformTransactionManager)
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2021, 广州九尾信息科技有限公司
 * @date 2021/6/21 14:17
 */
@Service
public class UserDaoImpl_XML implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PlatformTransactionManager transactionManager;

    @Override
    public int update(Long id) {
        //声明transactionDefinition
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(definition);
        //声明transactionStatus
        int update = 0;
        try {
            String sql = "update backstage_user set nickname= ? where id=?";
            Object[] objects = {"mojo2", 1};
            update = jdbcTemplate.update(sql, objects);
            List<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from backstage_user where id=1");
            for (Map<String, Object> map : maps) {
                System.out.println(map);
            }
            String insert = "insert into backstage_role (name,description) values(?,?,?)";
            Object[] objects1 = {"超管", "超级管理员"};
            int insert1 = jdbcTemplate.update(insert, objects1);
            transactionManager.commit(status);
        } catch (DataAccessException e) {
            e.printStackTrace();
            transactionManager.rollback(status);
        } catch (TransactionException e) {
            e.printStackTrace();
            transactionManager.rollback(status);
        }
        return update;
    }
}
